package com.polito.mad.bikeponyapp.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Base64;
import android.view.Menu;
import android.view.Surface;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

import com.polito.mad.bikeponyapp.R;
import com.polito.mad.bikeponyapp.fragments.FeedbackFragment;
import com.polito.mad.bikeponyapp.fragments.FeedbackFragment.OnFeedbackSaveListener;
import com.polito.mad.bikeponyapp.fragments.SignatureFragment;
import com.polito.mad.bikeponyapp.fragments.SignatureFragment.OnSignatureSaveListener;
import com.polito.mad.bikeponyapp.persistence.DeliveriesRepository;
import com.polito.mad.bikeponyapp.persistence.DeliveryItem;
import com.polito.mad.bikeponyapp.persistence.RepositoryHolder;
import com.polito.mad.bikeponyapp.util.AsyncTaskForResultMessage;
import com.polito.mad.bikeponyapp.util.DialogCreator;
import com.polito.mad.bikeponyapp.util.ResultMessage;

public class FeedbackActivity extends FragmentActivity implements
		OnSignatureSaveListener, OnFeedbackSaveListener {

	private static final String PREVIOUS_ORIENTATION_PARAM_NAME = "previous_orientation";
	private static final String DELIVERY_ID_PARAM_NAME = "deliveryId";
	private byte[] signatureImageBytes;
	//private long itemId = -1;
	private long deliveryId  = -1;//saqib: as item gets deleted as soon as the status is updated hence there is no guarantee as it can be deleted by service while trying to clear the item from the item list in the main activity, so not sure that item will still be there 

	private String sFeedbackAnswers = "";
	private int previousOrientation;
	private DeliveriesRepository deliveryRepo;
	
	private SignatureFragment mSignatureFragment;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_feedback);
		
		if (savedInstanceState != null	&& savedInstanceState.containsKey(PREVIOUS_ORIENTATION_PARAM_NAME)) {
			previousOrientation = savedInstanceState.getInt(PREVIOUS_ORIENTATION_PARAM_NAME);
			//itemId = savedInstanceState.getLong("itemId");
			deliveryId = savedInstanceState.getLong(DELIVERY_ID_PARAM_NAME);
			signatureImageBytes = savedInstanceState.getByteArray("signagureImageBytes");
			
		}
		int orientation = getScreenOrientation(this);
		previousOrientation = orientation;
		if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE || orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
			loadSignatureFragment();
		} else
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		getActionBar().setTitle(getString(R.string.title_activity_feedback));

		Bundle myBundle = this.getIntent().getExtras();
		if (myBundle != null) {
			deliveryId = myBundle.getLong(getString(R.string.delivery_id_notification_intent_param));
		}
		deliveryRepo = ((RepositoryHolder)getApplication()).getDeliveriesRepository();
		/*
		DeliveryItem item = deliveryRepo.get(itemId);
		if(item != null)
		{
			deliveryId = item.getDeliveryId();
		}
		*/
		
	}
	@Override
	public void onBackPressed() {
		//block the back while signature is being taken
	}
	private void loadSignatureFragment() {
		if (findViewById(R.id.fragment_container) != null) {

			FragmentManager fm = getSupportFragmentManager();
			mSignatureFragment = new SignatureFragment();

			// In case this activity was started with special instructions from
			// an Intent,
			// pass the Intent's extras to the fragment as arguments
			Bundle bundle = getIntent().getExtras();
			if(bundle != null)
			{
				bundle.putByteArray("signagureImageBytes", signatureImageBytes);
				mSignatureFragment.setArguments(bundle);
			}

			// Add the fragment to the 'fragment_container' FrameLayout
			fm.beginTransaction()
					.replace(R.id.fragment_container, mSignatureFragment)
					.commit();
			
			ImageButton tempButton = (ImageButton) findViewById(R.id.saveSignatureButton);
			if (tempButton != null) {

				tempButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {

						loadFeedbackFrag();
					}
				});
			}
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(PREVIOUS_ORIENTATION_PARAM_NAME, previousOrientation);
		
		//outState.putLong("itemId", itemId);
		outState.putLong(DELIVERY_ID_PARAM_NAME, deliveryId);
		
		if(mSignatureFragment != null)
		{
			signatureImageBytes = mSignatureFragment.getSignatureByteArray();
			
			
		}
		if(signatureImageBytes != null)
			outState.putByteArray("signagureImageBytes", signatureImageBytes);

		
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onPause() {
		
		if(mSignatureFragment != null)
			signatureImageBytes = mSignatureFragment.getSignatureByteArray();
		
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		if(mSignatureFragment != null && signatureImageBytes == null)
			signatureImageBytes = mSignatureFragment.getSignatureByteArray();
		
	}
	
	private void loadFeedbackFrag() {
		setRequestedOrientation(previousOrientation);
		FeedbackFragment newFragment = new FeedbackFragment();

		FragmentManager supportFragmentManager = getSupportFragmentManager();
		FragmentTransaction transaction = supportFragmentManager.beginTransaction();

		// transaction.remove(mSignatureFragment);
		// Replace whatever is in the fragment_container view with this
		// fragment,
		// and add the transaction to the back stack so the user can navigate
		// back
		transaction.replace(R.id.fragment_container, newFragment);
		transaction.addToBackStack(null);

		// Commit the transaction
		transaction.commit();

	}

	public byte[] getSignatureArray() {
		return signatureImageBytes;
	}
	
	public void setSignatureArray(byte[] signatureArray) {
		signatureImageBytes = signatureArray;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.test_surf_view, menu);
		// super.onCreateOptionsMenu(menu);
		return true;
	}

	@Override
	public void onSignatureSave(byte[] image) {

		signatureImageBytes = image;

		loadFeedbackFrag();
	}

	@Override
	public void onFeedbackSave(String sData) {
		sFeedbackAnswers = sData;
		this.updateDataToServer();
	}

	public void updateDataToServer() {
		StringBuilder b = new StringBuilder();
		b.append(getString(R.string.server_com_protocol))
				.append("://")
				.append(getString(R.string.server_host))
				.append(":")
				.append(getString(R.string.server_port))
				.append(getString(R.string.server_services_context_path))
				.append(getString(R.string.server_services_agent_path))
				.append(getString(R.string.server_services_agent_submit_signature));

		AsyncTaskForResultMessage asyncTask = new AsyncTaskForResultMessage(
				b.toString(), true,
				new AsyncTaskForResultMessage.OnTaskCompletionListener() {

					@Override
					public void onTaskEnded(ResultMessage resultMessage) {

						ProgressActivity.getInstance().finish();

						if (resultMessage.getStatusCode() == ResultMessage.STATUS_OK) {
							
							
							AlertDialog alertDialog = DialogCreator.createAlertDialog(FeedbackActivity.this, getString(R.string.feedback_data_saved_correctly), getString(R.string.notificaiton_delivery));
							alertDialog.setButton(Dialog.BUTTON_POSITIVE, "OK",new Dialog.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
									setResult(RESULT_OK);
									
									finish();
									
								}
							});
							alertDialog.show();
														
							setResult(RESULT_OK);
							
						} else {
							
							String sMessage = getString(R.string.error_sending_feedback);
							String sTitle = getString(R.string.feedback_alert_dialog_title);
							AlertDialog dialog = DialogCreator.createAlertDialog(FeedbackActivity.this, sMessage, sTitle);
							
							dialog.setButton(Dialog.BUTTON_POSITIVE, "RETRY",
									new Dialog.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											updateDataToServer();
										}
									});
							

							dialog.show();
						}

					}
				});

		ContentValues cv = new ContentValues();
		String agentId = PreferenceManager.getDefaultSharedPreferences(this).getString(getString(R.string.userid_pref), "");
		cv.put("agentId", agentId);
		
		cv.put(DELIVERY_ID_PARAM_NAME, deliveryId);

		String recipientSignature = Base64.encodeToString(signatureImageBytes, Base64.NO_WRAP);
		cv.put("recipientSignature", recipientSignature);
		cv.put("answers", sFeedbackAnswers);

		asyncTask.execute(cv);

		Intent intent = new Intent(getApplicationContext(), ProgressActivity.class);
		startActivity(intent);
	}

	public static int getScreenOrientation(Activity activity) {
		int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
		int orientation = activity.getResources().getConfiguration().orientation;
		if (orientation == Configuration.ORIENTATION_PORTRAIT) {
			if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270) {
				return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
			} else {
				return ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
			}
		}
		if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
			if (rotation == Surface.ROTATION_0	|| rotation == Surface.ROTATION_90) {
				return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
			} else {
				return ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
			}
		}
		return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
	}
}
